﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Converter;
using csla4Skeleton.UI.SL.Resources.Utility;
using csla4Skeleton.UI.SL.NghiepVu.TaiSanCoDinh.DM_DoiTuongTHCP;
using csla4Skeleton.UI.SL.DanhMuc.DM_HangHoa;
using Accounting.Library;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using System.ComponentModel;
using Utility;
using Telerik.Windows;
using Accounting.Library.Utility;
using csla4Skeleton.UI.SL.NghiepVu.TinhGiaThanh.GT_KyGiaThanh;

namespace csla4Skeleton.UI.SL.NghiepVu.TinhGiaThanh.GT_SoLuongSPDD
{
    public partial class GT_SoLuongSPDD_ChildWindow : ChildWindow, Csla.Xaml.ISupportNavigation
    {

        #region ISupportNavigation Members
        List<Control> controls = new List<Control>();
        public bool CreateBookmarkAfterLoadCompleted
        {
            get { return true; }
        }

        public event EventHandler LoadCompleted;
        public event EventHandler Saved;
        protected virtual void OnLoadCompleted()
        {
            if (LoadCompleted != null)
                LoadCompleted(this, EventArgs.Empty);
        }

        public void SetParameters(string parameters)
        {
            try
            {
                if (parameters == "")
                    Khoa = null;
                else
                    Khoa = Int32.Parse(parameters);
            }
            catch
            {
                Khoa = null;
            }
        }

        public string Title
        {
            get { return "SoLuongSPDD"; }
        }

       
        #endregion

        #region Load Methods
        private System.Nullable<int> Khoa = null;
        private GT_KyGiaThanhInfo KyGiaThanh;
        private string DienGiai;
        public int CountSave = 0;
        public event EventHandler OnClosedChildWindow;
        public event EventHandler TinhSoLuongSPDDCompleteted;
        List<GT_KyGiaThanhInfo> ResultList = new List<GT_KyGiaThanhInfo>();

        public GT_SoLuongSPDD_ChildWindow(int Khoa)          
        {
            this.Khoa = Khoa;

            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.TinhGiaThanh.GT_SoLuongSPDD.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.GT_SoLuongSPDD_ChungTuInformation_GroupBox, controls);
          
        }

        public GT_SoLuongSPDD_ChildWindow()
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.TinhGiaThanh.GT_SoLuongSPDD.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);
            
            InitializeComponent();  
            ControlBehavior.ControlBehaviors.Navigation(this.GT_SoLuongSPDD_ChungTuInformation_GroupBox, controls);
           
           
        }
        public GT_SoLuongSPDD_ChildWindow(GT_KyGiaThanhInfo kyGiaThanh, string DienGiai)
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.TinhGiaThanh.GT_SoLuongSPDD.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.GT_SoLuongSPDD_ChungTuInformation_GroupBox, controls);
           
            this.KyGiaThanh = kyGiaThanh;
            this.DienGiai = DienGiai;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
               
                System.Windows.Data.CollectionViewSource GT_SoLuongSPDD_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["GT_SoLuongSPDD_ViewModelSource"];
                if (Khoa == null)
                {
                    GT_SoLuongSPDD_ViewModel GT_SoLuongSPDD_ViewModel = new GT_SoLuongSPDD_ViewModel(BusinessConfiguration.Configuration.ChildWindow);
                    GT_SoLuongSPDD_ViewModel.ChildList_AddedNew += new GT_SoLuongSPDD_ViewModel.ChildList_AddedNew_EventHandler(GT_SoLuongSPDD_ViewModel_ChildList_AddedNew);              
                    GT_SoLuongSPDD_ViewModel.LoadCompleted += new EventHandler(GT_SoLuongSPDD_ViewModel_LoadCompleted);  
                    GT_SoLuongSPDD_ViewModel.Saved += new EventHandler(OnSaveCompleted);
                    GT_SoLuongSPDD_CollectionViewSource.Source = new List<object> { GT_SoLuongSPDD_ViewModel };
                  
            
                    
                    
                }
                else
                {
                    GT_SoLuongSPDD_ViewModel GT_SoLuongSPDD_ViewModel = new GT_SoLuongSPDD_ViewModel((int)Khoa);
                    GT_SoLuongSPDD_ViewModel.ChildList_AddedNew += new GT_SoLuongSPDD_ViewModel.ChildList_AddedNew_EventHandler(GT_SoLuongSPDD_ViewModel_ChildList_AddedNew);                   
                    GT_SoLuongSPDD_CollectionViewSource.Source = new List<object> { GT_SoLuongSPDD_ViewModel };

                    System.Windows.Data.CollectionViewSource gt_KyGiaThanh_ChiTiet_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["GT_KyGiaThanh_ChiTiet_ListViewModelSource"];
                    GT_KyGiaThanh_ListViewModel gt_KyGiaThanh_ChiTiet_ListViewModel = new GT_KyGiaThanh_ListViewModel(BusinessConfiguration.Configuration.KyGiaThanhFilterMode);
                    gt_KyGiaThanh_ChiTiet_CollectionViewSource.Source = new List<object> { gt_KyGiaThanh_ChiTiet_ListViewModel };

                    this.CountSave++;
                    GT_SoLuongSPDD_ViewModel.Saved += new EventHandler(OnSaveCompleted);
  
                }

              

                System.Windows.Data.CollectionViewSource gt_KyGiaThanh_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["GT_KyGiaThanh_ListViewModelSource"];
                GT_KyGiaThanh_ListViewModel gt_KyGiaThanh_ListViewModel = new GT_KyGiaThanh_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                gt_KyGiaThanh_CollectionViewSource.Source = new List<object> { gt_KyGiaThanh_ListViewModel };

                System.Windows.Data.CollectionViewSource dm_DoiTuongTHCP_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_DoiTuongTHCP_ListViewModelSource"];
                DM_DoiTuongTHCP_ListViewModel dm_DoiTuongTHCP_ListViewModel = new DM_DoiTuongTHCP_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_DoiTuongTHCP_CollectionViewSource.Source = new List<object> { dm_DoiTuongTHCP_ListViewModel };

                System.Windows.Data.CollectionViewSource dm_HangHoa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["DM_HangHoa_ListViewModelSource"];
                DM_HangHoa_ListViewModel dm_HangHoa_ListViewModel = new DM_HangHoa_ListViewModel(BusinessConfiguration.Configuration.ComboboxFetchMode);
                dm_HangHoa_CollectionViewSource.Source = new List<object> { dm_HangHoa_ListViewModel };

                this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView.KeyboardCommandProvider = new ControlBehavior.GridViewKeyboardCommandProvider(this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView);
                
                ((ControlBehavior.GridViewKeyboardCommandProvider)this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView.KeyboardCommandProvider).ReachLastColumn += new ControlBehavior.GridViewKeyboardCommandProvider.ReachLastColumn_EventHandler(OnReachLastColumn);

                ((ControlBehavior.GridViewKeyboardCommandProvider)this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView.KeyboardCommandProvider).TabKeyPress += new EventHandler(OnTabKeyPress);
            }
        }

        #endregion
       

        #region Event Handle
        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                GT_SoLuongSPDD_ViewModel vm = GetViewModel();
                if (e.Key == Key.S)
                {
                    if (vm.CanSave)
                    {
                        vm.Save(sender, new Csla.Xaml.ExecuteEventArgs());
                    }
                }
                else if (e.Key == Key.F6)
                {
                    AddItems();
                }
                else if (e.Key == Key.D1)
                {
                    this.GT_SoLuongSPDD_SoLuongSPDDChiTietTab.IsSelected = true;
                }
               
               
                
            }
            e.Handled = true;
        }

        void AddItemButton_Click(object sender, RoutedEventArgs e)
        {

            AddItems();
        }

        void DeleteItemButton_Click(object sender, RoutedEventArgs e)
        {
            DeleteItems();
          
        }
        protected override void OnClosed(EventArgs e)
        {
            if (OnClosedChildWindow != null)
            {
                OnClosedChildWindow(this, new EventArgs());
            }
            base.OnClosed(e);

        }
        public void AddItems()
        {
            if (this.GT_SoLuongSPDD_SoLuongSPDDChiTietTab.IsSelected)
            {
                AddSoLuongSPDDDetailsItem();
            }
        }
        private RadGridView GetActiveGridView()
        {
            if (this.GT_SoLuongSPDD_SoLuongSPDDChiTietTab.IsSelected)
            {
                return GT_SoLuongSPDD_SoLuongSPDDChiTietGridView;
            }
           
            return null;
        }

        void DeleteItems()
        {
           if (this.GT_SoLuongSPDD_SoLuongSPDDChiTietTab.IsSelected)
            {
                GT_SoLuongSPDD_ChiTietChild ChiTietChild = (GT_SoLuongSPDD_ChiTietChild)(this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView.SelectedItem);
                IList<GT_SoLuongSPDD_ChiTietChild> list = GetViewModel().Model.GT_SoLuongSPDD_ChiTiets;
                int index = list.IndexOf(ChiTietChild);
               
                DeleteSoLuongSPDDDeTailsItem(index);
            }
           
            
        }
           
        void GridView_AddingNewDataItem(object sender, GridViewAddingNewEventArgs e)
        {
            var grid = e.OwnerGridViewItemsControl;
            if (grid.Items.Count > 0)
            {
                GridViewUtil.FocusRow((RadGridView)grid, grid.Items.Count - 1);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
            }
        }
              
        private void SaveAndNewButton_Click(object sender, RoutedEventArgs e)
        {
           GT_SoLuongSPDD_ViewModel vm = GetViewModel();
            vm.SaveAndNew();
        }

        private void DatePicker_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddSoLuongSPDDDetailsItem();
                }
            }
            else
            {
                ControlBehavior.DatePickerBehaviors.DatePicker_KeyUp(sender, e, controls);
            }
        }

        private void ComboBox_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddSoLuongSPDDDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ComboBoxBehaviors.ComboBox_KeyUp(sender, e, controls);
            }
        }

        private void Control_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddSoLuongSPDDDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ControlBehaviors.Control_KeyUp(sender, e, controls);
            }
        }


        void OnTabKeyPress(object sender, EventArgs e)
        {
            this.tabControl.SelectedItem = tabControl.Items[0];
            this.AddSoLuongSPDDDetailsItem();
        }

        void OnReachLastColumn(object sender, ReachLastColumnArgs e)
        {

            List<TabItem> AvailableTabItem = new List<TabItem>();
            int indexCurrentTab = 0;
            foreach (TabItem item in this.tabControl.Items)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    AvailableTabItem.Add(item);
                    if (item.GetHashCode() == tabControl.SelectedItem.GetHashCode())
                    {
                        indexCurrentTab = AvailableTabItem.IndexOf(item);
                    }

                }
            }


            TabItem[] list = AvailableTabItem.ToArray();
            if (indexCurrentTab == (AvailableTabItem.Count - 1))
            {
                this.tabControl.SelectedItem = list[0];
                FocusAfterChangeTab(this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView, e.Index);

            }
            

        }

        private void FocusAfterChangeTab(GridViewDataControl grid, int index)
        {
             
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[index], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
           
        }
        
        
       
        #endregion

        #region View Model Related Methods
        public GT_SoLuongSPDD_ViewModel GetViewModel()
        {
            System.Windows.Data.CollectionViewSource GT_SoLuongSPDD_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["GT_SoLuongSPDD_ViewModelSource"];
            return ((List<object>)GT_SoLuongSPDD_CollectionViewSource.Source)[0] as GT_SoLuongSPDD_ViewModel;
        }


        private void GT_SoLuongSPDD_ViewModel_LoadCompleted(object sender, EventArgs e)
        {
            this.GetViewModel().Model.KyGiaThanhId = this.KyGiaThanh.Khoa;
            this.GetViewModel().Model.DienGiai = this.DienGiai;

            System.Windows.Data.CollectionViewSource gt_KyGiaThanh_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["GT_KyGiaThanh_ChiTiet_ListViewModelSource"];
            GT_KyGiaThanh_ListViewModel gt_KyGiaThanh_ListViewModel = new GT_KyGiaThanh_ListViewModel(BusinessConfiguration.Configuration.KyGiaThanhFilterMode);
            gt_KyGiaThanh_ListViewModel.LoadCompleted += new EventHandler(OnKyGiaThanhChiTietLoadCompleteted);
            gt_KyGiaThanh_CollectionViewSource.Source = new List<object> { gt_KyGiaThanh_ListViewModel };
        }


        void OnKyGiaThanhChiTietLoadCompleteted(object sender, EventArgs e)
        {

            IList<GT_SoLuongSPDD_ChiTietChild> listChiTiet = this.GetViewModel().Model.GT_SoLuongSPDD_ChiTiets;
            while (listChiTiet.Count != 0)
            {
                this.DeleteSoLuongSPDDDeTailsItem(0);
            }

            System.Windows.Data.CollectionViewSource gt_KyGiaThanh_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["GT_KyGiaThanh_ChiTiet_ListViewModelSource"];
            GT_KyGiaThanh_ListViewModel gt_KyGiaThanh_ListViewModel = ((List<object>)gt_KyGiaThanh_CollectionViewSource.Source)[0] as GT_KyGiaThanh_ListViewModel;
            IList<GT_KyGiaThanhInfo> listKyGiaThanh = gt_KyGiaThanh_ListViewModel.Model.getListOfInfo();

            foreach (GT_KyGiaThanhInfo item in listKyGiaThanh)
            {
                if (item.Khoa == this.GetViewModel().Model.KyGiaThanhId)
                {
                    ResultList.Add(item);
                    this.AddSoLuongSPDDDetailsItem();
                }
            }
            this.GetViewModel().CountChanged += new EventHandler(OnCountChanged);
        }

       
        public void OnCountChanged(object sender, EventArgs e)
        {
            IList<GT_SoLuongSPDD_ChiTietChild> listChiTiet = GetViewModel().Model.GT_SoLuongSPDD_ChiTiets;
            if (listChiTiet.Count == ResultList.Count)
            {
                GT_KyGiaThanhInfo[] KyGiaThanhArray = ResultList.ToArray();
                int index = 0;
                foreach (GT_SoLuongSPDD_ChiTietChild item in listChiTiet)
                {
                    item.DoiTuongTHCPId = KyGiaThanhArray[index].DoiTuongTHCPId;
                    item.HangHoaId = KyGiaThanhArray[index].HangHoaId;
                    index++;
                }
                this.GetViewModel().Save(this, new Csla.Xaml.ExecuteEventArgs());       
            }
   
        }
          
               
        private void OnSaveCompleted(object sender, EventArgs e)
        {
            
            if (TinhSoLuongSPDDCompleteted != null)
            {
                TinhSoLuongSPDDCompleteted(this, new EventArgs());
            }
        }
        private void AddSoLuongSPDDDetailsItem()
        {
            GetViewModel().AddGT_SoLuongSPDD_ChiTietItem();
        }
        private void DeleteSoLuongSPDDDeTailsItem(int Index)
        {
            GetViewModel().DeleteGT_SoLuongSPDD_ChiTietItem( Index);
        }

        void GT_SoLuongSPDD_ViewModel_ChildList_AddedNew(object sender, ChildListAddedNewArgs e)
        {
            if (e.ChildListName == "GT_SoLuongSPDD_ChiTiets")
            {
                this.GT_SoLuongSPDD_SoLuongSPDDChiTietGridView.OnAddingNewDataItem(new GridViewAddingNewEventArgs(GetActiveGridView()));
            }
   
        }

       
        #endregion
        
    }
}
